from django.template import RequestContext
from django.shortcuts import render_to_response
from django.conf import settings
from django import forms
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect,Http404
from django.contrib.auth.decorators import login_required

from pacs.models import Task,TaskResults,Submission,Compiler,GoalResults,TestResults
from ham.views import show_page
from forms import SubmissionManipulator

def _add_submission(task,user,comp,code):
	s = Submission(user=user,task=task,comp=comp,code=code)
	s.save()
	try:
		taskResults = TaskResults.objects.get(user=user,task=task)
	except TaskResults.DoesNotExist:
		taskResults = TaskResults(task=task,user=user)
	taskResults.submissions = taskResults.submissions+1
	taskResults.save()
	import os
	os.makedirs(os.path.join(settings.TESTS_PATH,str(task.problem.id),"pout",str(s.id)))
	return s

@login_required
def add_submission(request,task_slug=""):

	c = RequestContext(request)
	comps = [(comp.id,comp.name) for comp in Compiler.objects.all()]
	manipulator = SubmissionManipulator(comps)
	if request.POST:
		data = request.POST.copy()
		data.update(request.FILES)
		errors = manipulator.get_validation_errors(data)
		print data
		if not errors:
			manipulator.do_html2python(data)
			try:
				task = Task.objects.get(slug=data['task'])
			except Task.DoesNotExist:
				errors = {'task':_("Task not found.")}
			else:
				submission = _add_submission(task,request.user,Compiler.objects.get(id=int(data['compiler'])),data['code']['content'])
				return HttpResponseRedirect(reverse("pacs.views.show_submission",None,(),{'submission_id':submission.id}))
	else:
		data = {'task':task_slug}
		errors = {}
	c['form'] = forms.FormWrapper(manipulator,data,errors)
	return render_to_response('pacs/add_submission.xhtml', c)

def show_submission(request,submission_id):
	submission_id = int(submission_id)

	c=RequestContext(request)

	try:
		submission = Submission.objects.get(id=submission_id)
	except Submission.DoesNotExits:
		raise Http404
	
	#if not submission.published and submission.user != request.user:
	if submission.user != request.user:
		raise Http404

	goalsResults = GoalResults.objects.filter(submission = submission)
	testsResults = TestResults.objects.filter(submission = submission)
	tests = dict([(tr.test.id,{'name':tr.test.name,'time':tr.time,'maxTime':tr.test.maxTime,'status':tr.status,'comment':tr.comment}) for tr in testsResults])

	goals = [{'points':gr.points,'maxPoints':gr.goal.maxPoints,'status':gr.status,'tests':map(lambda t:tests.get(t.id),gr.goal.tests.all())} for gr in goalsResults]

	c['goals'] = goals

	return render_to_response('pacs/show_submission.xhtml',c)

def list_submissions(request,task_slug=None,page="0"):
	reqs = {}
	if task_slug is not None:
		try:
			reqs.update({'task':Task.objects.get(slug=task_slug)})
		except Task.DoesNotExist:
			raise Http404
	return show_page(request,int(page),Submission.objects.filter(*reqs).order_by('-insertTime'),'pacs/list_submissions.xhtml',3)

def list_my_submissions(request,task_slug=None,page="0"):
	reqs = {'user':request.user}
	if task_slug is not None:
		try:
			reqs.update({'task':Task.objects.get(slug=task_slug)})
		except Task.DoesNotExist:
			raise Http404
	return show_page(request,int(page),Submission.objects.filter(*reqs).order_by('-insertTime'),'pacs/list_submissions.xhtml',3)
